package edu.buaa.resourceManager.ui;

import edu.buaa.resourceManager.Config;
import edu.buaa.resourceManager.helper.Utils;
import javafx.concurrent.Worker;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.image.Image;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * Created by song on 2017/5/22 0022.
 */
public class WebViewWindow
{
    private static Logger log = LoggerFactory.getLogger("Amitabha");

    private static final double defaultHeight = 600;
    private static final double defaultWidth = 850;
    private static final String defaultTitle = "大通永利資源管理";
    private static final Image defaultIcon = new Image(WebViewWindow.class.getResourceAsStream("/logo.png"));


    private final Browser browser;
    private Stage curStage;
    private URL url;

    public WebViewWindow(URL url)
    {
        this(
                new Stage(),
                defaultTitle,
                defaultIcon,
                url,
                defaultWidth,
                defaultHeight);
    }

    public WebViewWindow(Stage stage, String title, Image icon, URL url, double width, double height) {
        this.curStage = stage;
        this.url = url;
        this.curStage.setTitle(title);
        this.browser = new Browser(url, this);
        Scene scene = new Scene(this.browser, width, height, Color.web("#666970"));
        this.curStage.setScene(scene);
        this.curStage.getIcons().add(icon);
//        this.curStage.getScene().getStylesheets().add("webviewsample/BrowserToolbar.css");
        this.curStage.show();
    }


    public String selectFile() {
        final FileChooser fileChooser = new FileChooser();
        File dir = new File(Config.get(Config.LAST_FILE_CHOOSE_DIR));
        Utils.getDevLogger().debug("{} {} {}", dir.getAbsolutePath(), dir.exists(), dir.isDirectory());
        if(dir.exists() && dir.isDirectory()) {
            fileChooser.setInitialDirectory(dir);
        }
        List<File> list = fileChooser.showOpenMultipleDialog(this.curStage);
        if (list != null) {
            StringBuilder sb = new StringBuilder();
            if(list.size()==1) {
                File file = list.get(0);
                Config.set(Config.LAST_FILE_CHOOSE_DIR, file.getParent());
                Utils.log.debug("{} {}", file.getAbsolutePath(), file.getParent());
                sb.append(file.getAbsolutePath());
            }else {
                for (File file : list) {
                    sb.append(file.getAbsolutePath()).append('\n');
                }
            }
            return sb.toString();
        }else{
            return "";
        }
    }

    public boolean openInFileExplorer(String path){
        try {
            Runtime.getRuntime().exec("explorer.exe /select," + path);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void waiting(){
        this.browser.blockRegion.setVisible(true);
        this.browser.progress.setVisible(true);
        this.browser.progress.setProgress(10);
    }

    public void openLinkInNewWindow(String url){
        try {
            new WebViewWindow(new URL(url));
        } catch (MalformedURLException e) {
            log.error("url format error", e);
        }
    }



    private static class Browser extends StackPane
    {
        final WebViewWindow win;
        final WebView browser = new WebView();
        final WebEngine webEngine = browser.getEngine();
        final private Region blockRegion = new Region();
        final private ProgressIndicator progress = new ProgressIndicator();

        public Browser(URL url, WebViewWindow window) {
            this.win = window;
            //apply the styles
//            getStyleClass().add("browser");

            blockRegion.setVisible(false);
            blockRegion.setStyle("-fx-background-color: rgba(0,0,0,0.4);");
            progress.setVisible(false);
            progress.setMaxHeight(150);
            progress.setMaxWidth(150);


            //add the web view to the scene
            getChildren().add(browser);
            getChildren().add(blockRegion);
            getChildren().add(progress);

            webEngine.setJavaScriptEnabled(true);

            webEngine.getLoadWorker().exceptionProperty().addListener((o‌​bs, oldExc, newExc) -> { if (newExc != null) { newExc.printStackTrace();}});
            com.sun.javafx.webkit.WebConsoleListener.setDefaultListener((webView, message, lineNumber, sourceId) -> log.error("Console: [" + sourceId + ":" + lineNumber + "] " + message));
//TODO https://github.com/mohamnag/javafx_webview_debugger
//            DevToolsDebuggerServer.startDebugServer(webEngine.impl_getDebugger(), 51742);
//            log.debug("bind {}", window);
            JSObject win = (JSObject) webEngine.executeScript("window");
            win.setMember("JavaApp", window);

            webEngine.setOnVisibilityChanged(event -> {
                log.debug("window close event: {} {}", event.getData(), event.toString());
                if(!event.getData()){
                    window.curStage.close();
                }
            });

//            webEngine.setCreatePopupHandler(
//                popupFeatures -> {
//
//                }
//            );

            webEngine.getLoadWorker().stateProperty().addListener(
                (ov, oldState, newState) -> {
                    log.trace("worker state change to: {}", newState);
                    if (newState == Worker.State.SUCCEEDED) {
                        JSObject w = (JSObject) webEngine.executeScript("window");
                        w.setMember("JavaApp", window);
                    }
                }
            );

            //adding context menu
            final ContextMenu cm = new ContextMenu();
//            MenuItem cmItem1 = new MenuItem("屏幕截图");
//            cm.getItems().add(cmItem1);
            browser.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
                if (e.getButton() == MouseButton.SECONDARY) {
                    cm.show(browser, e.getScreenX(), e.getScreenY());
                }
            });

            //processing print job
//            cmItem1.setOnAction((ActionEvent e) -> {
//                PrinterJob job = PrinterJob.createPrinterJob();
//                if (job != null) {
//                    webEngine.print(job);
//                    job.endJob();
//                }
//            });1
            // load the web page
            webEngine.load(url.toString());


        }

        @Override protected void layoutChildren() {
            double w = getWidth();
            double h = getHeight();
            layoutInArea(browser,0,0,w,h,0, HPos.CENTER, VPos.CENTER);
        }

        @Override protected double computePrefWidth(double height) {
            return 750;
        }

        @Override protected double computePrefHeight(double width) {
            return 500;
        }
    }
}
